<template>
    <div class="adduser">
        <Layout>
            <Header class="header">
                <Row>
                    <Col :span="20">
                        <div>
                            <span class="border-left"></span>
                            添加成员
                        </div>
                    </Col>
                    <Col :span="4">
                        <div class="back">
                            <span class="back-btn" @click="back">
                                <Icon type="ios-arrow-back" />
                                返回
                            </span>
                        </div>
                    </Col>
                </Row>
            </Header>
            <Content class="content">
                <div class="card-add">
                    <div class="ivu-card ivu-card-bordered ivu-card-dis-hover">
                        <div class="ivu-card-head">
                            <p data-v-57b29fc1="">添加成员</p>
                        </div>
                        <div class="ivu-card-body"> 
                            <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="120" style="width:40%">
                                <FormItem label="成员姓名" prop="name">
                                    <Input v-model="formValidate.name" />
                                </FormItem>
                                <FormItem label="登录账号" prop="account">
                                    <Input v-model="formValidate.account" placeholder="建议填写用户手机号或者电子邮箱"/>
                                </FormItem>
                                <FormItem :label="index === 0 ? '所属角色' : '角色'+(index + 1)" v-for="(item,index) in formValidate.role_id" :key="index" class="ivu-form-item-required">

                                        <!-- <Select v-model="formValidate.role_id[index]" @on-change="roleChange(index,formValidate.role_id[index])" v-if="index !== 0">
                                            <Option v-for="(role,index) in roles" :key="index" :value="role.id"  v-show="isAreaShow ? (role.id == 3 || role.id == 4 || role.id == 5) ? false : true : true">{{role.name}}</Option>
                                        </Select> -->
                                    <Row type="flex" justify="space-between" v-if="index !== 0">
                                        <Col span="18" style="padding:0">
                                            <Select v-model="formValidate.role_id[index]" @on-change="roleChange(index,formValidate.role_id[index])">
                                                <Option v-for="(role,index) in roles" :key="index" :value="role.id">{{role.name}}</Option>
                                                <!-- v-show="isAreaShow ? (role.id == 3 || role.id == 4 || role.id == 5) ? false : true : true" -->
                                            </Select>
                                        </Col>
                                        <Col span="4" style="padding:0">
                                            <Button style="width:100%" @click="minRole">-</Button>
                                        </Col>
                                    </Row>
                                    
                                    <Row type="flex" justify="space-between" v-else>
                                        <Col span="18" style="padding:0">
                                            <Select v-model="formValidate.role_id[0]" @on-change="roleChange(index,formValidate.role_id[index])">
                                                <Option v-for="(role,index) in roles" :key="index" :value="role.id">{{role.name}}</Option>
                                            </Select>
                                        </Col>
                                        <Col span="4" style="padding:0">
                                            <Button v-show="addBtn" style="width:100%" @click="addRole">+</Button>
                                        </Col>
                                    </Row>
                                </FormItem>
                                <FormItem label="代理区域（区县）" prop="area" class="hidden ivu-form-item-required" :class="isAreaShow(5) ? 'show' : ''">
                                    <Cascader :data="area" :load-data="loadAreaData" filterable v-model="formValidate.area"></Cascader>
                                </FormItem>
                                <FormItem label="代理区域（市级）" prop="town" class="hidden ivu-form-item-required" :class="isAreaShow(4) ? 'show' : ''">
                                    <Cascader :data="town" :load-data="loadTownData" filterable v-model="formValidate.town"></Cascader>
                                </FormItem>
                                <FormItem label="代理区域（省级）" prop="province" class="hidden ivu-form-item-required" :class="isAreaShow(3) ? 'show' : ''">
                                    <Cascader :data="province" filterable v-model="formValidate.province"></Cascader>
                                </FormItem>
                                <FormItem label="合伙人提成" prop="rate" class="hidden ivu-form-item-required" :class="isAreaShow(2) ? 'show' : ''">
                                    <Input v-model="formValidate.rate">
                                        <span slot="append">%</span>
                                    </Input>
                                </FormItem>
                                <!-- <FormItem label="服务提成（市级）" prop="rate" class="hidden ivu-form-item-required" :class="isAreaShow(4) ? 'show' : ''">
                                    <Input v-model="formValidate.rate">
                                        <span slot="append">%</span>
                                    </Input>
                                </FormItem>
                                <FormItem label="服务提成（省级）" prop="rate" class="hidden ivu-form-item-required" :class="isAreaShow(3) ? 'show' : ''">
                                    <Input v-model="formValidate.rate">
                                        <span slot="append">%</span>
                                    </Input>
                                </FormItem> -->
                                <FormItem label="登录密码" prop="new_password">
                                    <Input type="password" v-model="formValidate.new_password" />
                                </FormItem>
                                <FormItem label="确认密码" prop="confirmPassword" class="ivu-form-item-required">
                                    <Input type="password" v-model="formValidate.confirmPassword" />
                                </FormItem>
                                <FormItem label="备注信息" prop="remark">
                                    <Input v-model="formValidate.remark" type="textarea" :autosize="{minRows: 5,maxRows: 10}" placeholder="请输入内容"></Input>
                                </FormItem>
                                <FormItem>
                                    <Button type="primary" @click="handleSubmit('formValidate')">提交</Button>
                                    <Button @click="() => {$refs.formValidate.resetFields()}" style="margin-left: 8px">重置</Button>
                                </FormItem>
                            </Form>
                        </div>
                    </div>
                </div>
            </Content>
            <Footer>
                <p class="copy-right">Copyright © {{host}}, All Rights Reserved.</p>
            </Footer>
        </Layout>
    </div>
    
</template>

<script>
    import * as api from '@/api/api'
    export default {
        data(){
            //代理区域验证规则
            const territoryCheck = (rule, value, callback) => {
                if (this.roleState) {
                    if(value.length == 0) {
                        callback(new Error('请选择代理区域'));
                    }else {
                        callback();
                    }
                }else {
                    callback();
                }
            };
            //角色验证规则
            const roleCheck = (rule, value, callback) => {
                callback();
            };
            //服务提成验证规则
            const rateCheck = (rule, value, callback) => {
                if (this.roleState) {
                    if(value === '') {
                        callback(new Error('请填写服务提成'));
                    }else {
                        callback();
                    }
                }else {
                    callback();
                }
            };
            //确认密码验证规则
            const validatePassCheck = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次填写密码'));
                } else if (value !== this.formValidate.new_password) {
                    callback(new Error('两次密码不一致'));
                } else {
                    callback();
                }
            };
            return {
                host: window.location.host,
                loading: this.$store.state,
                roles: [],//角色列表
                //表单
                formValidate: {
                    name: '',//成员姓名
                    account: '',//成员账号
                    role_id: ['7'],//所属角色
                    area: [],//区域
                    town: [],
                    province: [],
                    rate: '',//服务提成
                    new_password: '',//密码
                    confirmPassword: '',//确认密码
                    remark: '',//备注
                },
                //验证规则
                ruleValidate: {
                    name: [
                        { required: true, message: '请填写成员姓名', trigger: 'blur' },
                    ],
                    role_id:[
                        { validator: roleCheck, trigger: 'change' }
                    ],
                    account: [
                        { required: true, message: '请填写登录账号', trigger: 'blur' }
                    ],
                    area: [
                        { validator: territoryCheck, trigger: 'blur' }
                    ],
                    town: [
                        { validator: territoryCheck, trigger: 'blur' }
                    ],
                    province: [
                        { validator: territoryCheck, trigger: 'blur' }
                    ],
                    rate: [
                        { validator: rateCheck, trigger: 'blur'}
                    ],
                    new_password: [
                        { required: true, message: '请填写登录密码', trigger: 'blur' },
                        { type: 'string', min: 6, message: '密码至少是6位字符', trigger: 'blur' }
                    ],
                    confirmPassword: [
                        { validator: validatePassCheck, trigger: 'change' }
                    ]
                },
                //状态
                roleState: '',//
                //区域选择---省/自治区/直辖市
                province: [],
                town: [],
                area: [],
                addBtn: true,
            }
        },
        mounted(){
            this.getRoles()
        },

        computed: {

        },

        watch: {
            
        },
        
        methods: {
            back() {
                this.$router.back();
            },
            addRole() {
                if(this.formValidate.role_id.length < 4) {
                    this.formValidate.role_id.push('');
                }else {
                    this.$Notice.error({
                        title: '错误',
                        desc: '最多只能添加4个角色',
                    });
                }
            },
            minRole() {
                let index = this.formValidate.role_id.length - 1;
                this.formValidate.role_id.splice(index, 1);
            },
            isAreaShow(i) {
                let flag = false;
                let str = this.formValidate.role_id.join(',');
                let reg = new RegExp(i);
                if(reg.test(str)) {
                    flag = true;
                }
                return flag;
            },
            roleChange(index,role) {
                // console.log(index,role,this.formValidate.role_id.length)
                // if(index === 0 && (role === '3' || role === '4' || role === '5') && this.formValidate.role_id.length > 1) {
                //     for (let i = 1; i < this.formValidate.role_id.length; i++) {
                //         this.formValidate.role_id[i] = '';
                //     }
                // }

                // let num = 0;
                // for (const item of this.formValidate.role_id) {
                //     if(item === '3' || item === '4' || item === '5') {
                //         num ++;
                //     }
                // }
                // if(num !== 0) {
                //     this.isAreaShow = true;
                //     if(role === '3' || role === '4' || role === '5') {
                //         this.roleState = role;
                //     }
                //     this.getProvince();
                // }else {
                //     this.isAreaShow = false;
                // }
            },
            //获取角色列表
            getRoles() {
                let body = {
                    model: 'Roles',
                    width: {
                        0: 'roleUsers'
                    },
                    contUser: '',
                    offset: 0,
                    limit: 10000,
                    condition: {},
                    search: {
                        is_delete: '0',
                        is_start: '1'
                    }
                };
                this.loading.isLoading = true;
                api.getDataList(body).then(res => {
                    if(res.data.code === 200) {
                        this.roles = res.data.data.data;
                        this.getProvince();
                    }
                    this.loading.isLoading = false;
                })
            },
            //省市区
            getProvince() {
                let body = {
                    model: 'Provinces',
                    limit: 1000,
                    offset: 0,
                    orderBy: 'id asc'
                };
                //省
                api.getDataList(body).then(res => {
                    let data = res.data.data.data;
                    // if(this.roleState === '3') {
                        for (const item of data) {
                            let one = {
                                value: item.province_name,
                                label: item.province_name,
                                id: item.id,
                                type: 0
                            };
                            this.province.push(one);
                        }
                    // }else {
                        for (const item of data) {
                            let areas = {
                                value: item.province_name,
                                label: item.province_name,
                                id: item.id,
                                children: [],
                                loading: false,
                                type: 0
                            };
                            let towns = {
                                value: item.province_name,
                                label: item.province_name,
                                id: item.id,
                                children: [],
                                loading: false,
                                type: 0
                            };
                            this.area.push(areas);
                            this.town.push(towns)
                        }
                    // }
                    // this.province = province;
                })
            },

            loadAreaData(item, callback) {
                this.loadData(1,item,callback);
            },

            loadTownData(item, callback) {
                this.loadData(2,item,callback);
            },

			loadData(status,item, callback) {
				item.loading = true;
				if (item.type === 0) {
					let body = {
						model: 'Citys',
						limit: 1000,
						offset: 0,
						orderBy: 'id asc',
						condition: {
							province_id: item.id
						}
					};
					//市
					api.getDataList(body).then(res => {
						let data = res.data.data.data;
						let city = [];
						if (status === 2) {
							for (const citys of data) {
								let one = {
									value: citys.city_name,
									label: citys.city_name,
									id: citys.id,
									type: 1
								};
								city.push(one)
							}
						} else {
							for (const citys of data) {
								let one = {
									value: citys.city_name,
									label: citys.city_name,
									id: citys.id,
									children: [],
									loading: false,
									type: 1
								};
								city.push(one)
							}
						}
						item.children = city;
						item.loading = false;
						callback();
					})
				} else if (item.type === 1) {
					let body = {
						model: 'Areas',
						limit: 1000,
						offset: 0,
						orderBy: 'id asc',
						condition: {
							city_id: item.id
						}
					};
					//区
					api.getDataList(body).then(res => {
						let data = res.data.data.data;
						let area = [];
						for (const areas of data) {
							let one = {
								value: areas.area_name,
								label: areas.area_name,
							};
							area.push(one)
						}
						item.children = area;
						item.loading = false;
						callback();
					})
				}

			},

            handleSubmit(name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        console.log(this.formValidate);
                        return false;
                        let data = this.formValidate;
                        let roles = data.role_id.join(',');
                        var territory = '';
                        // debugger;
                        if(data.province.length > 0) {
                            territory = territory + data.province.join(',');
                        }
                        if(data.town.length > 0) {
                            if(territory) {
                                territory = territory + '&' + data.town.join(',');
                            }else {
                                territory = territory + data.town.join(',');
                            }
                                
                        }
                        if(data.area.length > 0) {
                            if(territory) {
                                territory = territory + '&' + data.area.join(',');
                            }else {
                                territory = territory + data.area.join(',');
                            }
                        }
                        let body = {
                            model: 'Users',
                            data: {
                                account: data.account,
                                name: data.name,
                                new_password: data.new_password,
                                role_id: roles,
                                territory,
                                remark: data.remark
                            }
                        };
                        if(body.data.role_id == '2' && data.rate) {
                            body.data.rate = data.rate;
                        }
                        // console.log(body);
                        // return false;
                        this.loading.isLoading = true;
                        api.createData(body).then(res => {
                            this.loading.isLoading = false;
                            if(res.data.code === 200) {
                                this.$Notice.success({
                                    title: '提示',
                                    desc: '恭喜你，添加成功！'
                                });
                                this.$router.push({name: 'UserList'})
                            }
                        })
                    }else {
                        console.log('err')
                    }
                })
            }
        }  
    }
</script>


<style lang="less">
    @import '../../../assets/styles/constant.less';
    .adduser{
        width: 100%;
        height: 100%;
        overflow-x: hidden;
        overflow-y: auto;
        background-color: #f5f7f9;
        .ivu-layout{
            min-height: 100%;
        }
        .header{
            font-size: 14px;
            line-height: 40px;
            height: 40px !important;
            color: #434343;
            padding: 0 50px;
            background-color: @background;
            border-bottom: 1px solid #ddd;
            .border-left {
                border-left: 5px solid @baseColor;
                margin-right: 4px;
            }
            .back{
                text-align: right;
                color: #999;
                .back-btn{
                    cursor: pointer;
                    background-color: #fff;
                    padding: 6px 10px;
                    border: 1px solid #ddd;
                }
            }
        }
        .content{
            width: 100%;
            min-height: 76%;
            padding: 20px 60px;
            .card-add{
                margin-top: 20px;
                .ivu-card-head{
                    background-color: #f2f2f2;
                }
                .ivu-card-body{
                    display: flex;
                    justify-content: space-around;
                }
                .hidden{
                    height: 0;
                    overflow: hidden;
                    transition: all 0.3s;
                    margin-bottom: 0;
                }
                .hidden.show{
                    height: 33px;
                    margin-bottom: 24px;
                    overflow:initial;
                }
            }
        }
        .copy-right{
            text-align: center;
            color: #aaa;
            font-size: 12px;
        }
    }
</style>